我可以在 C++ 中创建不同数据类型的构造函数吗?
Can I make a constructor in C++ of different data types?
我有一个 class,它有多个不同数据类型的数据成员。我想知道是否可以使用构造函数创建和初始化对象。
class test
{
public:
int a;
string b;
float c;
test (int x, string y, float z);
};
int main()
{
test t1(10,"Hello",2.5f); //this line doesn't work
}
您需要实现构造函数test (int x, std::string y, float z);
不要忘记#include <string>
在源文件的顶部。
尽管您可以使用符号
test t1{10, "Hello", 2.5f};
这将使参数按照写入的顺序分配给 class 成员;尽管您将不得不完全放弃构造函数。
在您的示例中,您声明了构造函数,但从未定义它。
class test
{
public:
int a;
std::string b;
float c;
test(int x, std::string y, float z) : a(x), b(y), c(z) {}
};
int main()
{
test t1(10, "Hello", 2.5f);
}
它不起作用 的事实并不是我们在 Whosebug 上所做的。您应该提供一条错误消息。
话虽如此,我想您从链接器中得到了一个错误,因为您的构造函数不包含定义,而只包含声明。
这是一个工作示例:https://godbolt.org/z/r89cf86s3
#include <string>
class test
{
public:
int a;
std::string b;
float c;
test (int x, std::string y, float z) : a{x}, b{y}, c{z}
{}
};
int main()
{
test t1(10, "Hello", 2.5f);
}
注意 将 std::string
按值传递给构造函数会导致创建临时对象,因此要保持此代码的工作并改进它,您可以使用const 引用,即 const std::string&
作为构造函数的参数。
我忘了定义构造函数:(
应该是这样的:-
class test
{
public:
int a;
string b;
float c;
test (int x, string y, float z)
{
a=x;
b=y;
c=z;
}
};
int main()
{
test t1(10,"Hello",2.5f); //this line doesn't work
}
我有一个 class,它有多个不同数据类型的数据成员。我想知道是否可以使用构造函数创建和初始化对象。
class test
{
public:
int a;
string b;
float c;
test (int x, string y, float z);
};
int main()
{
test t1(10,"Hello",2.5f); //this line doesn't work
}
您需要实现构造函数test (int x, std::string y, float z);
不要忘记#include <string>
在源文件的顶部。
尽管您可以使用符号
test t1{10, "Hello", 2.5f};
这将使参数按照写入的顺序分配给 class 成员;尽管您将不得不完全放弃构造函数。
在您的示例中,您声明了构造函数,但从未定义它。
class test
{
public:
int a;
std::string b;
float c;
test(int x, std::string y, float z) : a(x), b(y), c(z) {}
};
int main()
{
test t1(10, "Hello", 2.5f);
}
它不起作用 的事实并不是我们在 Whosebug 上所做的。您应该提供一条错误消息。
话虽如此,我想您从链接器中得到了一个错误,因为您的构造函数不包含定义,而只包含声明。
这是一个工作示例:https://godbolt.org/z/r89cf86s3
#include <string>
class test
{
public:
int a;
std::string b;
float c;
test (int x, std::string y, float z) : a{x}, b{y}, c{z}
{}
};
int main()
{
test t1(10, "Hello", 2.5f);
}
注意 将 std::string
按值传递给构造函数会导致创建临时对象,因此要保持此代码的工作并改进它,您可以使用const 引用,即 const std::string&
作为构造函数的参数。
我忘了定义构造函数:(
应该是这样的:-
class test
{
public:
int a;
string b;
float c;
test (int x, string y, float z)
{
a=x;
b=y;
c=z;
}
};
int main() {
test t1(10,"Hello",2.5f); //this line doesn't work
}