![](/img/trans.png)
[英]Member functions in terms of private getters and setters in C++ class?
[英]C++ Member Functions (getters)
我見過人們這樣定義成員 function:
void getValue(int& v)
{
v = m_value;
}
也像這樣:
int getValue()
{
return m_value;
}
我猜第一個保存 memory? 那是你唯一一次使用第一種類型的 get 函數嗎? 第二個似乎更方便。
我以為我會為你神栓
來源
#include <iostream>
struct Foof{
int m_val;
Foof(int v){
m_val = v;
}
void woodle()
{
if(m_val > 42)
m_val++;
else
m_val--;
}
void Get1(int &v)
{
v = m_val;
}
int Get2()
{
return m_val;
}
};
int main(int c, char**v){
int q;
std::cin >> q;
Foof f1(q);
std::cin >> q;
Foof f2(q);
f1.woodle();
f2.woodle();
int k;
f1.Get1(k);
int j = f2.Get2();
std::cout << k << j;
}
woodle function 和 cin 初始化是為了讓編譯器思考一下
我有 2 個錯誤,否則當我在 Get1 之后調用 Get2 時,編譯器會“我知道這個問題的答案”
用-03編譯——即努力優化。 代碼輸出為 (gcc)
pushq %rbx
movl $_ZSt3cin, %edi
subq $16, %rsp
leaq 12(%rsp), %rsi
call std::basic_istream<char, std::char_traits<char> >::operator>>(int&)
movl 12(%rsp), %ebx
leaq 12(%rsp), %rsi
movl $_ZSt3cin, %edi
call std::basic_istream<char, std::char_traits<char> >::operator>>(int&)
movl 12(%rsp), %eax
movl $_ZSt4cout, %edi
leal 1(%rbx), %edx
cmpl $43, %ebx
leal -1(%rbx), %esi
cmovge %edx, %esi
leal -1(%rax), %ebx
leal 1(%rax), %edx
cmpl $43, %eax
cmovge %edx, %ebx
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
movq %rax, %rdi
movl %ebx, %esi
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
addq $16, %rsp
xorl %eax, %eax
popq %rbx
ret
我將對 Get1 或 Get2 的實際調用分開,您可以看到
課程,將代碼編寫為人類可讀,讓編譯器完成繁重的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.