gpt4 book ai didi

c++ - 关于通过 Get 和 Set 方法传递字符串

转载 作者:行者123 更新时间:2023-11-28 03:20:39 24 4
gpt4 key购买 nike

首先让我说我是 C++ 的初学者。我正在尝试编写一个只要求用户输入 3 次的程序。两个是字符串,一个是整数。我为此编写了以下类(class):

#include <string>
#include <sstream>

using namespace std;

class Cellphone
{
private :
string itsbrand;
string itscolor;
int itsweight;

public :
string tostring();
void setbrand(string brand);
string getbrand() ;
void setcolor(string color);
string getcolor();
void setweight(int weight);
int getweight();


};

除我需要两个构造函数外,一切都完全按照我的需要进行。一种参数中没有数据,一种参数中有数据。我什至不知道要从构造函数开始,所以如果有人能提供一点见解,我将不胜感激。这是我的 main() :

int main ()
{
Cellphone Type;

int w;
string b, c;

cout << "Please enter the Cellphone brand : ";
getline(cin, b);
Type.setbrand (b);
cout << "Please enter the color of the Cellphone : ";
getline(cin, c);
Type.setcolor (c);
cout << "Please enter the weight of the Cellphone in pounds : ";
cin >> w;
Type.setweight (w);
cout << endl;
cout << Type.tostring();
cout << endl;
}

关于我将如何做构造函数的任何想法?

最佳答案

C++ 类中的构造函数可以重载。

  1. 没有给定参数的构造函数通常称为“默认构造函数”。如果你的类没有定义任何构造函数,则编译器将为您生成一个“默认构造函数”。 “默认构造函数”是可以在不提供任何参数的情况下调用的构造函数。

  2. 给定参数的构造函数在这些参数被使用时被使用 在创建类的新对象时提供值。如果 你的类已经定义了一个带有参数的构造函数,然后 编译器不会为你生成“默认构造函数”,所以当 您创建一个需要默认构造函数的对象,它将 导致编译错误。因此,是否提供默认构造函数和重载构造函数取决于您的应用程序。

例如,在您的 CellPhone 类中,您可以根据需要提供两个或更多构造函数。

默认构造函数:您正在为类的成员提供某种默认值

public CellPhone(): itsbrand(""), itscolor(""), itsweight(0){ 
//note that no formal parameters in CellPhone parameter list
}

带参数的构造函数:

public CellPhone(string b, string c, int w): itsbrand(b), itscolor(c), itsweight(w)
{
}

您还可以定义一个为所有给定参数提供默认值的构造函数,根据定义,这也称为“默认构造函数”,因为它们具有默认值。示例如下:

public CellPhone(string b="", string c="", int w=0): itsbrand(b),itscolor(c),itsweight(w)
{
}

这些是关于 C++ 中构造函数重载的一些方面;

关于c++ - 关于通过 Get 和 Set 方法传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15514886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com