C++如何在类构造函数中使用另一个(用户定义的)类作为参数

C++ How to use another (user-defined) class as an argument in a class constructor

本文关键字:定义 用户 参数 构造函数 C++ 另一个      更新时间:2023-10-16

我似乎在任何地方都找不到这个,所以希望以前没有人问过它。我正在重新学习c++,想尝试解决上次遇到的一个问题,但无法解决;生成两个复杂的类(笛卡尔类和极性类),它们具有彼此具有自变量的构造函数。我遇到的问题是,第一个类似乎无法识别第二个类的存在,因此我无法在构造函数中使用它。

我的代码的精简版本:

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){
                       ^

我知道最好尝试在一节课上完成这一切,但如果我不解决它,这会让我感到困扰,任何帮助都将不胜感激!

您只需要显式转发声明complex_rt,因为friend声明似乎不起作用:

class complex_rt;
class complex_ab{
friend class complex_rt;
...

完整示例:http://ideone.com/Q8GkQh