在c++中创建和初始化类
Creating and initializing classes in C++
我正在学习在c++中创建类,我已经创建了一个简单的Point类。它不知何故不能编译,我不知道出了什么问题。请帮助。
Point.h
#ifndef POINT_H
#define POINT_H
class Point {
private:
float x, y;
public:
//default constructor
Point();
//constructor
Point(float x, float y);
float getX();
float getY();
void print();
};
#endif
Point.cpp
#include "Point.h"
Point::Point(){
x = 0.0;
y = 0.0;
};
Point::Point(float x, float y){
x = x;
y = y;
}
float Point::getX(){
return x;
}
float Point::getY(){
return y;
}
void Point::print(){
cout << "hello" ;
{
main.cpp:
#include <Point.h>
#include <iostream>
int main()
{
Point p(10.0f, 20.0f);
p.print();
return 0;
}
下面是构建消息:
||=== Build: Debug in Point (compiler: GNU GCC Compiler) ===|
main.cpp|7|error: no matching function for call to 'Point::Point(float, float)'|
main.cpp|8|error: 'class Point' has no member named 'print'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
您在定义body时忘记将Point::
放在print
前面。此外,构造函数中的x = x
不会做任何事情。您需要分配给this->x
, y也是如此。
如果可能,总是使用构造函数初始化列表
Point::Point()
: x(0.f)
, y(0.f)
{
}
Point::Point(float x, float y)
: x(x)
, y(y)
{
}
getX() getY()返回const
相关文章:
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- GLEW/GLUT:调用init并创建一个窗口后,取消初始化并重新初始化?
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 设置 JVM 通过 JNI 初始化时创建的线程数
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 创建 std::thread 时出现错误 C2280,未在 C++ 中初始化
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 在成员初始化列表中,我可以创建对列表中不在列表中的成员变量的引用
- 从现有 istream 或类本身创建的 istream 初始化成员 istream
- 无序列图会创建一个零初始化结构吗?
- 可以使用C 结构汇总初始化来创建临时实例
- 在此初始化中创建的临时对象数
- 当我初始化了指针属性 allready 时,如何将 QGraphicsItem 向下投射到创建的类?
- MPI - 当数组初始化值必须为常量时,如何为工作线程创建部分数组
- 如何正确创建、初始化和访问类的静态成员
- C++ 在堆上创建数组而不对其进行初始化
- 在c++上创建税务计算程序,错误为未初始化的局部变量
- 如何创建一个编译时静态类类型,该类型初始化具有特定值的成员容器
- 未初始化的值是由堆分配创建的:Unordered_map