c++ - C++ 新手的类成员函数

标签 c++ member-functions

我是 C++ 新手,目前正在准备考试,在 VisualStudio 中尝试使用 C++ 并进行一些实验。我通常使用 Java。

我编写了一个简单的类来查看事情如何以及是否有效:

class Point
{
private:
    int x;
    int y;

public:
    Point(int arg1, int arg2)
    {
        x = arg1;
        y = arg2;
    }
};

我为 x 和 y 尝试了 2 个简单的成员函数,将 x 和 y 变量中存储的值加倍。

首先我尝试了这个:

void doubleX()
{
    x *= 2;
};

void doubleY()
{
    y *= 2;
};

然后我尝试了这个:

void doubleX()
{
    Point::x = 2 * Point::x;
};

void doubleY()
{
    Point::y = 2 * Point2::y;
};

两者都放在类定义中。

通过 VisualStudio 构建时,它总是给我这个错误警告: “错误 C3867 'Point::doubleX':非标准语法;使用 '&' 创建指向成员的指针”

也尝试过使用地址指针,但是......我真的不知道。 我想我知道指针基本上是如何工作的,但我不知道如何在我的案例中使用它。

这个问题有什么快速的解决方案和解释吗?

提前致谢!

编辑:这是我的整个代码,问题现在主要在

    #include "stdafx.h"
#include <iostream>

using namespace std;

class Point
{
public:
    int x;
    int y;

    Point(int arg1, int arg2)
    {
        x = arg1;
        y = arg2;
    }

    void doubleX()
    {
        x *= 2;
    };

    void doubleY()
    {
        y *= 2;
    };
};

int main()
{
    Point p(1,1);

    int &x = p.x;
    int &y = p.y;

    cout << x << "|" << y;

    p.doubleX; p.doubleY; //error message here

    cout << x << "|" << y;

    cin.get();
}

最佳答案

也许您没有在类定义中内部声明成员函数?这是基于您的类(class)的完整工作示例:

#include <iostream>


class Point
{
private:
    int x;
    int y;

public:
    Point(int arg1, int arg2)
    {
        x = arg1;
        y = arg2;
    }

    void doubleX()
    {
        x *= 2; /* or this->x *= 2; */
    }

    void doubleY()
    {
        y *= 2;
    }

    int getX()
    {
        return x;
    }

    int getY()
    {
        return y;
    }
};


int main()
{
    Point p(2, 3);

    std::cout << "p.x = " << p.getX() << " | p.y = " << p.getY() << std::endl;

    p.doubleX();
    p.doubleY();

    std::cout << "p.x = " << p.getX() << " | p.y = " << p.getY() << std::endl;

    return 0;
}

您可以将其放入 main.cpp 文件中,编译并运行它。我用 g++ 编译器测试了它,它工作得很好。

关于c++ - C++ 新手的类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45169427/

相关文章:

c++ - 编译器为类创建的所有成员函数是什么?这是否一直发生?

c++ - 使用和重载基类的模板成员函数?

c++ - OpenGL 将 glutSpecialFunc 指向成员函数

c++ - 即使在相同字符串之间进行比较,strcmp() 也会返回错误值

c++ - 访问内存映射寄存器

c++ - 这个功能声明得好吗?

C++03.在编译时测试 rvalue-vs-lvalue,而不仅仅是在运行时

c++ - 仅在类的第一个实例初始化时调用的成员函数 (C++)

c++ - CPP 模板化成员函数特化

javascript 构造函数未正确绑定(bind)