【问题标题】:C++ How to use another (user-defined) class as an argument in a class constructorC ++如何在类构造函数中使用另一个(用户定义的)类作为参数
【发布时间】:2015-09-19 21:16:01
【问题描述】:

我似乎在任何地方都找不到这个,所以希望以前没有人问过这个问题。我正在重新学习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){
                       ^

我知道在一节课上尝试做这一切可能会更好,但如果我不解决这个问题,我会很烦,任何帮助将不胜感激!

【问题讨论】:

  • 我在这里没有看到任何问题,除了您发布了代码的剥离版本的可能性。
  • @Ajay 通过剥离我刚刚删除了与问题无关的重载运算符声明,错误消息来自这个确切的代码(其他部分已注释掉)

标签: c++ class constructor arguments


【解决方案1】:

您只需要显式转发声明complex_rt,因为friend 声明似乎没有这样做:

class complex_rt;

class complex_ab{
friend class complex_rt;
...

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

【讨论】:

  • 如果这是真的,模板元编程根本就行不通。
  • @Ajay,嗯,确实。事实证明,他所需要的只是前向声明。改变了我的答案。
  • 谢谢,它工作得很好,我明白为什么它工作了我只是在将它们定义为函数之前从未考虑过声明类。
猜你喜欢
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多