簡體   English   中英

在 OOP 的構造函數中將字符串輸入作為參數

[英]taking string input as parameter in constructor in OOP

當我創建 class 網站的實例時,此代碼顯示錯誤。 該實例必須使用我在 class 定義中定義的顯式構造函數。 所以我在其中傳遞了一個字符串值。 該值由構造函數中的字符類型數組接收,然后初始化指向該數組的指針。 請避免給出復雜的答案。

#include<iostream>
#include<conio.h>
using namespace std;

class Links
{
private:
    char *linkname;
public:
    Links()
    {
        cout << "Links default constructor called." << endl;
    };
    Links(char n[]):linkname(n)
    {
        cout << "Links parameterized constructor called." << endl;
    };
    char getlinkname()
    {
        return *linkname;
    }
    void setlinkname(char n[])
    {
        linkname = n;
    }
};

class Webpage
{
private:
    double width;
    double height;
    Links link1;
    Links link2;
public:
    Webpage()
    {
        cout << "Webpage default constructor called." << endl;
    };
    Webpage(double w, double h) :width(w), height(h)
    {
        cout << "Webpage parameterized constructor called." << endl;
    };
    double getheight()
    {
        return height;
    }
    double getwidth()
    {
        return width;
    }
    void setheight(double h)
    {
        height = h;
    }
    void setwidth(double w)
    {
        width = w;
    }
};

class Website
{
private:
    char *name;
    Webpage webpage1{24.5,37.2};
    Webpage webpage2;
    Webpage webpage3{10,18.7};
    Webpage webpage4;
public:
    Website()
    {
        cout << "Website default constructor called." << endl;
    };
    Website(char n[]):name(n)
    {
        cout << "Website parameterized constructor called." << endl;
    };
    char getname()
    {
        return *name;
    }
    void setname(char n[])
    {
        name = n;
    }

};

int main()
{
    Website w1("www.google.com");
    
    _getch();
    return 0;
}

字符串文字是'const',試試這個:

class Website
{
private:
    const char *name;
    Webpage webpage1{24.5,37.2};
    Webpage webpage2;
    Webpage webpage3{10,18.7};
    Webpage webpage4;
public:
    Website()
    {
        cout << "Website default constructor called." << endl;
    };
    Website(const char* n):name(n)
    {
        cout << "Website parameterized constructor called." << endl;
    };
    const char* getname()
    {
        return name;
    }
    void setname(const char* n)
    {
        name = n;
    }

};

暫無
暫無

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

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