簡體   English   中英

C ++如何在類構造函數中使用另一個(用戶定義的)類作為參數

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

我似乎無法在任何地方找到它,因此希望從未有人問過。 我正在重新學習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){
                       ^

我知道最好在一堂課上嘗試全部操作,但這會惹惱我,如果我不解決的話,任何幫助將不勝感激!

您只需要顯式轉發聲明complex_rt ,因為friend聲明似乎不這樣做:

class complex_rt;

class complex_ab{
friend class complex_rt;
...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM