C++ 如何使用另一个(用户定义的)class 作为 class 构造函数中的参数
C++ How to use another (user-defined) class as an argument in a class constructor
我似乎无法在任何地方准确找到它,希望之前没有人问过它。我正在重新学习c++,想尝试解决一个我上次遇到但无法解决的问题;制作 2 个复杂的 classes(笛卡尔坐标和极坐标坐标),它们的构造函数具有彼此的参数。我遇到的问题是第一个 class 似乎无法识别第二个 class 的存在,因此我无法在构造函数中使用它。
我的代码的精简版:
class complex_ab{
friend class complex_rt;
public:
complex_ab(): a(0), b(0) { }
complex_ab(const double x, const double y): a(x), b(y) { }
complex_ab(complex_rt);
~complex_ab() { }
private:
double a, b;
};
class complex_rt{
friend class complex_ab;
public:
complex_rt(): r(0), theta(0) { }
complex_rt(const double x, const double y): r(x), theta(y) { }
complex_rt(complex_ab);
~complex_rt() { }
private:
double r, theta;
};
和 .cpp 文件
#include "complex.h"
#include <cmath>
#include <iostream>
using namespace std;
complex_ab::complex_ab(complex_rt polar){
a = polar.r * cos(polar.theta);
b = polar.r * sin(polar.theta);
}
complex_rt::complex_rt(complex_ab cart){
r = sqrt(cart.a * cart.a + cart.b * cart.b);
theta = atan(cart.b/cart.a);
}
主文件目前只有 returns 0,而我试图编译它。我得到的错误是
error: field 'complex_rt' has incomplete type 'complex_ab'
complex_ab(complex_rt);
^
note: definition of 'class complex_ab' is not complete until the closing brace
class complex_ab{
出于某种原因我得到了两次,然后
error: expected constructor, destructor, or type conversion before '(' token
complex_ab::complex_ab(complex_rt polar){
^
我知道尝试一次完成所有操作可能会更好class,但如果我不解决这个问题,我会很烦恼,任何帮助将不胜感激!
您只需要显式前向声明 complex_rt
,因为 friend
声明似乎没有这样做:
class complex_rt;
class complex_ab{
friend class complex_rt;
...
我似乎无法在任何地方准确找到它,希望之前没有人问过它。我正在重新学习c++,想尝试解决一个我上次遇到但无法解决的问题;制作 2 个复杂的 classes(笛卡尔坐标和极坐标坐标),它们的构造函数具有彼此的参数。我遇到的问题是第一个 class 似乎无法识别第二个 class 的存在,因此我无法在构造函数中使用它。
我的代码的精简版:
class complex_ab{
friend class complex_rt;
public:
complex_ab(): a(0), b(0) { }
complex_ab(const double x, const double y): a(x), b(y) { }
complex_ab(complex_rt);
~complex_ab() { }
private:
double a, b;
};
class complex_rt{
friend class complex_ab;
public:
complex_rt(): r(0), theta(0) { }
complex_rt(const double x, const double y): r(x), theta(y) { }
complex_rt(complex_ab);
~complex_rt() { }
private:
double r, theta;
};
和 .cpp 文件
#include "complex.h"
#include <cmath>
#include <iostream>
using namespace std;
complex_ab::complex_ab(complex_rt polar){
a = polar.r * cos(polar.theta);
b = polar.r * sin(polar.theta);
}
complex_rt::complex_rt(complex_ab cart){
r = sqrt(cart.a * cart.a + cart.b * cart.b);
theta = atan(cart.b/cart.a);
}
主文件目前只有 returns 0,而我试图编译它。我得到的错误是
error: field 'complex_rt' has incomplete type 'complex_ab'
complex_ab(complex_rt);
^
note: definition of 'class complex_ab' is not complete until the closing brace
class complex_ab{
出于某种原因我得到了两次,然后
error: expected constructor, destructor, or type conversion before '(' token
complex_ab::complex_ab(complex_rt polar){
^
我知道尝试一次完成所有操作可能会更好class,但如果我不解决这个问题,我会很烦恼,任何帮助将不胜感激!
您只需要显式前向声明 complex_rt
,因为 friend
声明似乎没有这样做:
class complex_rt;
class complex_ab{
friend class complex_rt;
...