我在SO上看到了一些关于Big-Three和复制交换的问答.的确,我学到了一些新东西,但有一点我不太明白.
为什么operator =返回引用而不是指针?
如果我有两个A和B类,我做A = B,调用赋值构造函数?A级或B级的那个?
令人怀疑的结果如下代码:
public static void main (String[] args)
{
int i = 2;
i = i+=2 + i++;
System.out.println(i); }
Run Code Online (Sandbox Code Playgroud)
期待8作为输出,因为'i + = 2'应该更新 i,但它不表现如此.
产量:6
我推断短手赋值运算符按预期返回4但不在变量i中更新相同.任何解释将不胜感激.
正如标题所描述的那样,a= b || c在shell脚本中执行or-assignment(例如)的正确方法是什么,特别是csh vs bash?我无法测试这个,所以也许上面的例子可行.
我认为这在脚本语言中很常见,但对于那些不太了解的人来说,变量a将保留bif truthy的值,否则保留值c.在该示例中b和c是表达式.
用例通常设置为a某种值(如果提供),否则使用默认值(例如a= $1 || "Foo").
由于这个问题并非如此,我不确定接近投票的原因是什么:
如果您需要进一步解释并需要一些修改,请发表评论.
我想int *x通过int *y使用表达式来交换指向的值
*x ^= *y ^= *x ^= *y;
Run Code Online (Sandbox Code Playgroud)
(好吧,我知道这个表达很尴尬,我只是想知道它的区别,没有冒犯.)这在C++中有效,但在C中失败了.但是如果我把它分成三部分,如下所示
*x ^= *y;
*y ^= *x;
*x ^= *y;
Run Code Online (Sandbox Code Playgroud)
它适用于两种语言.
那么,^=C和C++ 中的运算符有什么区别?
我在C中使用了这样的构造:
list->head = list->tail = NULL;
Run Code Online (Sandbox Code Playgroud)
现在我考虑这是否真的意味着我想的.
这是什么意思?
list->head = NULL; list->tail = NULL;要么
list->head = list->tail; list->tail = NULL;thx澄清
对于课程A,我们可以使用
A& operator=( A other ) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
代替
A& operator=( const A& other ) { /* ... */ }
A& operator=( const A&& other ) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
没有恶化的表现或其他负面影响?
我在网上看到的一些赋值重载操作符示例如下所示:
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
void operator = (const Distance &D ) {
cout << "assigning..." << endl;
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << …Run Code Online (Sandbox Code Playgroud) 例如,给定结构S:
typedef struct {
int a, b;
} S;
Run Code Online (Sandbox Code Playgroud)
...以及一个带指针的方法S,我可以在一行中为它分配聚合初始值设定项1的值吗?这是我使用临时的现有解决方案:
void init_s(S* s) {
S temp = { 1, 2 };
*s = temp;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用C11.
1对于那些不了解我的问题的非常罕见的超级学生,因为不知何故"聚合初始化器"在这里不适用,因为LHS没有声明一个新对象,我的意思是"聚合初始化器一样的语法与括号和东西".
c compound-literals assignment-operator aggregate-initialization c11
问题很简单.
这是模板化operator = for的声明std::any:
template<typename ValueType>
any& operator=( ValueType&& rhs );
Run Code Online (Sandbox Code Playgroud)
我希望它是:
template<typename ValueType>
any& operator=( ValueType&& rhs ) noexcept(noexcept(std::declval<std::any>() = std::forward<ValueType>(std::declval<ValueType>()));
Run Code Online (Sandbox Code Playgroud)
也就是说,如果您可以以noexcept方式将ValueType复制分配给任何一个,那么您应该能够使用noexcept.
也许我错过了什么.