以下哪个示例是声明以下功能的更好方法?为什么?
void myFunction (const int &myArgument);
Run Code Online (Sandbox Code Playgroud)
要么
void myFunction (int myArgument);
Run Code Online (Sandbox Code Playgroud) 在C++中是否有一种规则或指导,当一个必须或至少应该选择使用引用传递而不是值时?
如果知道(小老实说)对象的大小与某个对象有关,则很难判断.
我无法理解以下代码的输出:-
#include <iostream>
using namespace std;
template <typename T>
void fun(const T&x){
static int count = 0;
cout << "x = " << x << " count = " << count << endl;
++count;
return;
}
int main(){
fun(1);
fun('A');
fun(1.1);
fun(2.2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Output:-
x = 1 count = 0
x = A count = 0
x = 1.1 count = 0
x = 2.2 count = 1
Run Code Online (Sandbox Code Playgroud)
如果每次调用函数时都将静态变量 count 的值重新分配为 0,那么为什么在第四次调用该函数时它会变为 1。还有一件事,我们不能直接传递“T x”而不是“ const T&x …
我有一个基类/父类:Person
还有两个子类/子类:Player,Coach
这就是基类Person的标题:
class Person
{
public:
Person(string name);
Person();
virtual ~Person();
string getName();
void setName(string name);
virtual void printSpec() const = 0;
private:
string name;
};
Run Code Online (Sandbox Code Playgroud)
我试图编译并运行,它开始抱怨这个:
include\Person.h||In constructor 'Coach::Coach(std::string, std::string)':|
include\Person.h|19|error: 'std::string Person::name' is private|
\src\Coach.cpp|5|error: within this context|
||=== Build finished: 2 errors, 0 warnings ===|
Run Code Online (Sandbox Code Playgroud)
并指出:
private:
string name;
Run Code Online (Sandbox Code Playgroud)
在子类"Coach"的两个构造函数中的一个的上下文中:
Coach::Coach(string name, string responsibility): Person(name){
this->name = name;
this->responsibility = responsibility;
}
Run Code Online (Sandbox Code Playgroud)
但是,它并没有对"Player"类的构造函数中的同一行提出相同的抱怨,只是在"Coach"类的构造函数中抱怨"字符串名称是私有成员".
我为其他人查找了一些解决方案,尝试保护而不是私有,尝试更改变量的名称,但没有用.
是什么赋予了?
将参数传递给将在短时间内调用数百万次的函数和方法时,传递所述参数的开销开始显示.
void foo(const SomeType&st){...}
对于像std :: string,std :: vector等类型...规则是通过引用传递,以便不会发生无意义的副本.然而,当处理诸如双打,英特等的POD时,故事却完全不同.
关于性能,如果函数/方法不需要改变参数,在决定是否应该通过引用,const引用或复制传递时,常见的"需要注意的事项"是什么?
void foo1(SomeType& st)
{
...
}
void foo2(const SomeType& st)
{
...
}
void foo3(SomeType st)
{
...
}
void foo4(SomeType* st)
{
...
}
Run Code Online (Sandbox Code Playgroud)
注意:这不是关于const正确性的问题.还在32/64位平台上寻找与gcc和msvc相关的答案.
一些可能相关的问答:
c++ ×5
class ×1
const ×1
function ×1
inheritance ×1
oop ×1
parent ×1
performance ×1
private ×1
templates ×1