gpt4 book ai didi

c++ - 声明类成员函数

转载 作者:行者123 更新时间:2023-11-30 05:41:41 26 4
gpt4 key购买 nike

我有一点 C++ 背景,但刚刚开始接触该语言的面向对象编程方面。我正在阅读有关类格式化的 C++ 教程网站。我读到可以在类中声明一个函数,然后使用作用域运算符::在类外定义它。鉴于我的经验不足,我想知道函数在类内定义是否更受欢迎,还是在类外定义更受欢迎,或者这是否真的无关紧要。

来自 C++ 教程网站

// classes example
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}

意思是,在类中只包含 set_values 定义不是更紧凑和更有效吗?

一如既往,谢谢。

最佳答案

通常声明在 .h 文件中,而定义在同名的 .cpp 文件中。

例子:

矩形.h:

class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};

矩形.cpp:

#include <rectangle.h>

void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}

这有助于将您的代码分发给其他人。您可以只分发一个 .dll 和一个 .h 供其他人使用,将您的实际代码保存在 .cpp 文件中。

.h 文件开始增长时,它也很有用。上千行的 .cpp 文件并不少见。遍历所有这些只是为了找到该类的公共(public)接口(interface)将需要付出很多努力。

注意:.h.cpp 只是约定。您可能会发现其他类似 .cxx.inl(用于内联函数)。

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

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