C++如何在类构造函数中使用另一个(用户定义的)类作为参数
C++ How to use another (user-defined) class as an argument in a class constructor
我似乎在任何地方都找不到这个,所以希望以前没有人问过它。我正在重新学习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
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- Visual C++(VS2017)中用户定义的转换不明确
- 使用用户定义的参数调用future/async并调用类方法
- 带有用户定义类的c++折叠表达式
- g++用户定义的动态链接库上的全局new和delete运算符
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 修改"std::set"中用户定义类型的值
- 参数包构造函数在类模板中隐藏用户定义的转换
- MAKE:找不到包含的用户定义的头文件?
- C++:用户定义的显式类型转换函数错误
- 是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
- 从 QAbstractItemModel 返回自定义用户类型
- 无法引用自定义用户控件
- Lua:为自定义用户数据提供一个字符串方法
- 是否可以在visualstudio调试窗口中定义用户定义的变量
- 如何在编写自定义用户操作时引用内置操作
- C++自定义用户输入调用变量
- 不能定义用户定义的字面值