在c++中创建和初始化类

Creating and initializing classes in C++

本文关键字:初始化 创建 c++      更新时间:2023-10-16

我正在学习在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

相关文章: