我似乎无法在任何地方找到这一点,所以希望它之前没有被问过。我正在重新学习c ++并想尝试解决我上次遇到但无法解决的问题;制作2个具有彼此参数的构造函数的复杂类(笛卡儿和极坐标)。我遇到的问题是第一个类似乎没有认识到第二个类存在,并且我不能在构造函数中使用它。
我的代码的精简版:
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);
}
当我尝试编译时,主文件当前只返回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){
^
我知道尝试在一个班级中完成这一切可能会更好但是如果我将其解决,这将会让我感到不安,任何帮助都将不胜感激!
答案 0 :(得分:0)
您只需明确转发声明complex_rt
,因为friend
声明似乎不会这样做:
class complex_rt;
class complex_ab{
friend class complex_rt;
...